﻿#include "stdafx.h"
#include "DataBuffer.h"
#include "DebugAssert.h"

_NAMESPACE_BEGIN

Buffer::Buffer( DWORD capacity/*=8*/ )
{
	size=pos=0;
	if(capacity>0)
	{newarray(b,__byte,capacity);}
	else
		b=NULL;
	this->capacity=capacity;
	candelete=true;
}

Buffer::~Buffer()
{
	if(candelete)
		delarray(b);
}

void Buffer::SetBuffer( __byte* ptr,DWORD len )
{
	delarray(b);
	pos=0;
	size=capacity=len;
	b=ptr;
	candelete=false;
}

void Buffer::SetCapacity( DWORD c )
{
	assert(0!=c);
	if(0==capacity)
	{
		if (c > 8)
		{
			capacity = c;
		}
		else
		{
			capacity = 8;
		}
	}

	while(c>capacity)
	{
		capacity*=2;
	}
	if(b)
	{
		__byte* t;
		newarray(t,__byte,capacity);
		memcpy(t,b,size);
		delarray(b);
		b=t;
	}
	else
		newarray(b,__byte,capacity);
}

void Buffer::Clear()
{
	if(candelete)
	{delmem(b);}
	else
		b=NULL;
	capacity=size=pos=0;
	candelete=true;
}

_NAMESPACE_END